"""
统一 API 路由 - 供 Web Frontend 调用
整合天气、导航、AI文本、TTS、音乐生成功能
"""
from flask import request, current_app, jsonify
from flask_restx import Namespace, Resource, fields

api = Namespace('api', description='统一API接口')

# ==================== 请求/响应模型 ====================

location_model = api.model('Location', {
    'latitude': fields.Float(required=True, description='纬度'),
    'longitude': fields.Float(required=True, description='经度')
})

poi_search_model = api.model('POISearch', {
    'latitude': fields.Float(required=True),
    'longitude': fields.Float(required=True),
    'radius': fields.Integer(default=3000, description='搜索半径（米）')
})

route_model = api.model('Route', {
    'start_lat': fields.Float(required=True),
    'start_lng': fields.Float(required=True),
    'end_lat': fields.Float(required=True),
    'end_lng': fields.Float(required=True)
})

text_gen_model = api.model('TextGeneration', {
    'poi_name': fields.String(required=True, description='景点名称'),
    'poi_category': fields.String(required=True, description='景点类别'),
    'poi_description': fields.String(description='景点描述'),
    'weather': fields.Raw(description='天气信息')
})

tts_model = api.model('TTS', {
    'text': fields.String(required=True, description='要转换的文本'),
    'voice': fields.String(default='alloy', description='语音类型')
})

music_gen_model = api.model('MusicGeneration', {
    'poi_name': fields.String(required=True),
    'poi_category': fields.String(required=True),
    'weather_condition': fields.String(default='晴'),
    'mood': fields.String(default='relaxing')
})


def get_unified_service():
    """获取统一服务实例"""
    from app.services.unified_service import UnifiedService
    return UnifiedService()


# ==================== 天气 API ====================

@api.route('/weather')
class WeatherAPI(Resource):
    """天气服务API"""
    
    def get(self):
        """
        获取当前天气
        
        Query Parameters:
            latitude: 纬度
            longitude: 经度
        """
        latitude = request.args.get('latitude', type=float)
        longitude = request.args.get('longitude', type=float)
        
        if latitude is None or longitude is None:
            return {'success': False, 'error': 'latitude和longitude参数必填'}, 400
        
        service = get_unified_service()
        result = service.get_weather(latitude, longitude)
        return result, 200


# ==================== POI搜索 API ====================

@api.route('/pois')
class POISearchAPI(Resource):
    """POI搜索API"""
    
    def get(self):
        """
        搜索附近POI
        
        Query Parameters:
            latitude: 纬度
            longitude: 经度
            radius: 搜索半径（米），默认3000
        """
        latitude = request.args.get('latitude', type=float)
        longitude = request.args.get('longitude', type=float)
        radius = request.args.get('radius', type=int, default=3000)
        
        if latitude is None or longitude is None:
            return {'success': False, 'error': 'latitude和longitude参数必填'}, 400
        
        service = get_unified_service()
        result = service.search_pois(latitude, longitude, radius)
        return result, 200


# ==================== 路线规划 API ====================

@api.route('/route')
class RouteAPI(Resource):
    """步行路线API"""
    
    @api.expect(route_model)
    def post(self):
        """获取步行路线"""
        data = request.get_json()
        
        required = ['start_lat', 'start_lng', 'end_lat', 'end_lng']
        for field in required:
            if field not in data:
                return {'success': False, 'error': f'{field}参数必填'}, 400
        
        service = get_unified_service()
        result = service.get_walking_route(
            data['start_lat'], data['start_lng'],
            data['end_lat'], data['end_lng']
        )
        return result, 200
    
    def get(self):
        """
        获取步行路线（GET方式）
        
        Query Parameters:
            start_lat, start_lng: 起点坐标
            end_lat, end_lng: 终点坐标
        """
        start_lat = request.args.get('start_lat', type=float)
        start_lng = request.args.get('start_lng', type=float)
        end_lat = request.args.get('end_lat', type=float)
        end_lng = request.args.get('end_lng', type=float)
        
        if None in [start_lat, start_lng, end_lat, end_lng]:
            return {'success': False, 'error': '起点和终点坐标参数必填'}, 400
        
        service = get_unified_service()
        result = service.get_walking_route(start_lat, start_lng, end_lat, end_lng)
        return result, 200


# ==================== AI文本生成 API ====================

@api.route('/ai/introduction')
class AIIntroductionAPI(Resource):
    """AI景点介绍生成API"""
    
    @api.expect(text_gen_model)
    def post(self):
        """生成景点介绍文本"""
        data = request.get_json()
        
        if not data.get('poi_name') or not data.get('poi_category'):
            return {'success': False, 'error': 'poi_name和poi_category参数必填'}, 400
        
        service = get_unified_service()
        result = service.generate_poi_introduction(
            poi_name=data['poi_name'],
            poi_category=data['poi_category'],
            poi_description=data.get('poi_description', ''),
            weather=data.get('weather')
        )
        return result, 200


# ==================== TTS语音合成 API ====================

@api.route('/ai/tts')
class TTSAPI(Resource):
    """TTS语音合成API"""
    
    @api.expect(tts_model)
    def post(self):
        """文本转语音"""
        data = request.get_json()
        
        if not data.get('text'):
            return {'success': False, 'error': 'text参数必填'}, 400
        
        service = get_unified_service()
        result = service.text_to_speech(
            text=data['text'],
            voice=data.get('voice', 'alloy')
        )
        
        if result.get('success'):
            return result, 200
        else:
            return result, 503


# ==================== 音乐生成 API ====================

@api.route('/ai/music')
class MusicGenerationAPI(Resource):
    """背景音乐生成API"""
    
    @api.expect(music_gen_model)
    def post(self):
        """生成背景音乐"""
        data = request.get_json()
        
        if not data.get('poi_name') or not data.get('poi_category'):
            return {'success': False, 'error': 'poi_name和poi_category参数必填'}, 400
        
        service = get_unified_service()
        result = service.generate_music(
            poi_name=data['poi_name'],
            poi_category=data['poi_category'],
            weather_condition=data.get('weather_condition', '晴'),
            mood=data.get('mood', 'relaxing')
        )
        return result, 200


# ==================== 服务状态 API ====================

@api.route('/status')
class ServiceStatusAPI(Resource):
    """服务状态检查API"""
    
    def get(self):
        """检查各服务状态"""
        import os
        
        status = {
            'weather': {
                'configured': bool(os.getenv('QWEATHER_KEY')),
                'fallback': True,
                'description': '和风天气API（未配置时使用mock数据）'
            },
            'map': {
                'configured': bool(os.getenv('TENCENT_MAP_KEY')),
                'fallback': True,
                'description': '腾讯地图API（POI搜索、路线规划）'
            },
            'ai_text': {
                'configured': bool(os.getenv('OPENAI_API_KEY')),
                'fallback': True,
                'description': 'OpenAI文本生成（未配置时使用模板）'
            },
            'tts': {
                'configured': bool(os.getenv('OPENAI_API_KEY')),
                'fallback': False,
                'description': 'OpenAI TTS语音合成'
            },
            'music': {
                'configured': bool(os.getenv('SUNO_API_KEY')),
                'fallback': True,
                'description': 'Suno音乐生成（未配置时使用预设音乐）'
            }
        }
        
        all_ready = all(s['configured'] or s['fallback'] for s in status.values())
        
        return {
            'success': True,
            'ready': all_ready,
            'services': status,
            'message': '所有服务已就绪' if all_ready else '部分服务需要配置'
        }, 200


# ==================== 综合接口 API ====================

@api.route('/walk/start')
class WalkStartAPI(Resource):
    """开始散步 - 综合接口"""
    
    def post(self):
        """
        开始散步，返回天气、附近POI、推荐路线
        
        Request Body:
            latitude: 当前纬度
            longitude: 当前经度
        """
        data = request.get_json()
        
        latitude = data.get('latitude')
        longitude = data.get('longitude')
        
        if latitude is None or longitude is None:
            return {'success': False, 'error': 'latitude和longitude参数必填'}, 400
        
        service = get_unified_service()
        
        # 获取天气
        weather = service.get_weather(latitude, longitude)
        
        # 搜索附近POI
        pois = service.search_pois(latitude, longitude, 3000)
        
        # 如果有POI，获取到第一个POI的路线
        route = None
        if pois.get('data') and len(pois['data']) > 0:
            first_poi = pois['data'][0]
            route = service.get_walking_route(
                latitude, longitude,
                first_poi.get('latitude', first_poi.get('location', {}).get('lat')),
                first_poi.get('longitude', first_poi.get('location', {}).get('lng'))
            )
        
        return {
            'success': True,
            'data': {
                'weather': weather.get('data'),
                'weather_suitable': weather.get('is_suitable', True),
                'weather_warning': weather.get('warning'),
                'pois': pois.get('data', []),
                'recommended_route': route.get('data') if route else None
            },
            'is_mock': weather.get('is_mock') or pois.get('is_mock')
        }, 200
